# !/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : 大野
import logging
from logging import handlers
import time
import os

path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class Log(object):
    def __init__(self):
        self.logname = "mylog"

    def setMSG(self, level, msg, when='D', backCount=7, fmt='%(asctime)s - %('
                                                            'levelname)s: %(message)s'):
        logger = logging.getLogger()
        request_time = time.strftime('%Y%m%d', time.localtime(time.time()))
        filename = path + '/report/log/' + request_time + '.txt'
        # 定义Handler输出到文件和控制台
        fh = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
                                               encoding='utf-8')
        ch = logging.StreamHandler()
        # 定义日志输出格式
        formater = logging.Formatter(fmt)
        fh.setFormatter(formater)
        ch.setFormatter(formater)
        # 添加Handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        # 添加日志信息，输出INFO级别的信息
        logger.setLevel(logging.INFO)
        if level == 'debug':
            logger.debug(msg)
        elif level == 'info':
            logger.info(msg)
        elif level == 'warning':
            logger.warning(msg)
        elif level == 'error':
            logger.error(msg)
        # 移除句柄，否则日志会重复输出
        logger.removeHandler(fh)
        logger.removeHandler(ch)
        fh.close()

    def debug(self, msg):
        self.setMSG('debug', msg)

    def info(self, msg):
        self.setMSG('info', msg)

    def warning(self, msg):
        self.setMSG('warning', msg)

    def error(self, msg):
        self.setMSG('error', msg)
        # raise Exception(msg)


if __name__ == '__main__':
    Log().warning("warning测试")
    Log().info("info测试")
    Log().error("ERROR")
